//
//  ScheduleViewController.m
//  project
//
//  Created by 圆圆陈 on 2017/12/16.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "ScheduleViewController.h"
#import "EditScheduleViewController.h"
#import "HistoryViewController.h"
#import <UserNotifications/UserNotifications.h>
@interface ScheduleViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,assign)BOOL selected;
@end

@implementation ScheduleViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self performSelector:@selector(updateTableView) withObject:nil afterDelay:0.1];
}

- (void)updateTableView
{
    NSMutableArray *tmpArr = SN_USER.showCalendarArray.mutableCopy;
    NSMutableArray *arr = SN_USER.showCalendarArray.mutableCopy;
    for (int i=0; i<SN_USER.showCalendarArray.count; i++) {
        SNcalendarModel *model = SN_USER.showCalendarArray[i];
        if ([model.date compare:[NSDate date]]==0 || [model.date compare:[NSDate date]]==-1) {
            //删除当前的model
            [arr removeObject:model];
            if(IOS10_OR_LATER){
                [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
            }else{
                [[UIApplication sharedApplication] cancelAllLocalNotifications];
            }
            [SN_USER.historyArray addObject:model];
        }
    }
    //将数组中剩余model的orderIndex重置
    for (int j=0; j<arr.count; j++) {
        SNcalendarModel *showModel =arr[j];
        showModel.orderIndex=j;
        [arr replaceObjectAtIndex:j withObject:showModel];
    }
    SN_USER.showCalendarArray = arr.mutableCopy;
    //往数组中添加初始化的model 便于覆盖calendarArray中的model
    NSMutableArray *secArr = arr.mutableCopy;
    for (int k=0; k<(tmpArr.count-arr.count); k++) {
        SNcalendarModel *model = [[SNcalendarModel alloc]init];
        model.orderIndex = arr.count+k;
        [secArr addObject:model];
    }
    //覆盖
    for (int h=0; h<secArr.count; h++) {
        [SN_USER.calendarArray replaceObjectAtIndex:h withObject:secArr[h]];
    }
    [self resetNotificationWithArr:SN_USER.showCalendarArray];
    [SN_EveryDayModelHelp startSetCalendar];
    
    [SN_USER updateToDB];
    [_tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *StateView = [[UIView alloc] init];
    StateView.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 20);
    StateView.backgroundColor = BBIGSTATECOLOR;
    [self.view addSubview:StateView];
    
    UIView *naView = [[UIView alloc] init];
    naView.frame = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:naView];
    
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20),screenWidth, 44)];
    lable.textColor=UIColorHEX(0x161616);
    lable.font= SNFONTMEDIUM(17);
    lable.textAlignment = NSTextAlignmentCenter;
    lable.text = HHH_Text(@"日程提醒");
    
    [self.view addSubview:lable];
    
    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    [leftButton addTarget:self action:@selector(leftbuttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    UIButton *rightButton = [[UIButton alloc] init];
    rightButton.frame = CGRectMake(HHHWIDTH-44, 20+FitSimpleIpx(0, 20), 44, 44);
    [rightButton setImageNormal:@"添加加号无边框"];
    [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightButton];

    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20)+44+10, HHHWIDTH, HHHHEIGHT-20-FitSimpleIpx(0, 20)-44-2) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource =self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    
    UIView *uiview = [[UIView alloc] init];
    uiview.frame = SNFRAME(0, 0, HHHWIDTH, 56);
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 6, HHHWIDTH -10, 44)];
    label.textColor = UIColorHEX(0x161616);
    label.text      = SN_Text(@"最多可以设置5个日程");
    label.font = SNFONTMEDIUM(17);
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    [uiview addSubview:label];
    
    _tableView.tableFooterView = uiview;
    
//    SNShadowView *shadowLine = [[SNShadowView alloc] init];
//    shadowLine.frame = SNFRAME(0,20+FitSimpleIpx(0, 20) + 44, HHHWIDTH, 0);
//    [shadowLine showWithType:1];
//    [self.view addSubview:shadowLine];
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
//    [self.view addSubview:shadowLine];
    
    self.view.backgroundColor = UIColorHEX(0xf0f2f5);
}
- (void)leftbuttonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rightButtonClick:(UIButton *)sender{
    sender.enabled = NO;
    EditScheduleViewController *editVC = [EditScheduleViewController new];
    editVC.type=0;
    editVC.model = [[SNcalendarModel alloc]init];
    [self.navigationController pushViewController:editVC animated:YES];
     sender.enabled = YES;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 0.01;
    }else{
        return 0.01;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [UIView new];
    if (section == 0) {
        view.backgroundColor = [UIColor blackColor];
    }
    else
    {
        view.backgroundColor = SNCOLORSEPRATE;
    }
    return view;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return section==0?1:SN_USER.showCalendarArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
  
    cell.textLabel.font = SNFONTMIN(15.0);
    if (indexPath.section==0) {
        cell.imageView.image = UIImageNamed(@"日程(1)");
        cell.textLabel.text = HHH_Text(@"历史日程提醒");
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 14, 24)];
        [imageView setImage:UIImageNamed(@"next")];
        cell.accessoryView =imageView;
    }else{
        SNcalendarModel *model = SN_USER.showCalendarArray[indexPath.row];
        cell.textLabel.text = model.info;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld-%02ld-%02ld %02ld:%02ld",model.year,model.month,model.day,model.hours,model.mins];
        cell.detailTextLabel.textColor = SNCOLORGRAY;
    }
    cell.textLabel.font = [UIFont systemFontOfSize:FitFont(18)];
    
    UIView*view1 = [[UIView alloc] initWithFrame:SNFRAME(0, 70, screenWidth, 10)];
    view1.backgroundColor = UIColorHEX(0xf0f2f5);
    [cell addSubview:view1];
    
    UIView*view2 = [[UIView alloc] initWithFrame:SNFRAME(20, 5, screenWidth-20, 0.5)];
    view2.backgroundColor = UIColorHEX(0xd9d9d9);
    [view1 addSubview:view2];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selected==NO) {
        self.selected = YES;
        if (indexPath.section==0) {
            HistoryViewController *historyVC = [HistoryViewController new];
            [self.navigationController pushViewController:historyVC animated:YES];
        }else{
            EditScheduleViewController *editVC = [EditScheduleViewController new];
            editVC.type=1;
            editVC.model = SN_USER.showCalendarArray[indexPath.row];
            [self.navigationController pushViewController:editVC animated:YES];
        }
        self.selected = NO;
    }
    
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        return YES;
    }else{
        return NO;
    }
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return   UITableViewCellEditingStyleDelete;
}
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:HHH_Text(@"删除")  handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        //删除当前的model
        if(IOS10_OR_LATER){
             [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
        }else{
             [[UIApplication sharedApplication] cancelAllLocalNotifications];
        }
        [SN_USER.showCalendarArray removeObjectAtIndex:indexPath.row];
        //将数组中剩余model的orderIndex重置
        for (int i=0; i<SN_USER.showCalendarArray.count; i++) {
            SNcalendarModel *showModel =SN_USER.showCalendarArray[i];
            showModel.orderIndex=i;
            [SN_USER.showCalendarArray replaceObjectAtIndex:i withObject:showModel];
        }
        //往数组中添加初始化的model 便于覆盖calendarArray中的model
        SNcalendarModel *model = [[SNcalendarModel alloc]init];
        model.orderIndex =SN_USER.showCalendarArray.count;
        [SN_USER.showCalendarArray addObject:model];
        //覆盖
        for (int i=0; i<SN_USER.showCalendarArray.count; i++) {
            [SN_USER.calendarArray replaceObjectAtIndex:i withObject:SN_USER.showCalendarArray[i]];
        }
        [self resetNotificationWithArr:SN_USER.showCalendarArray];
        [SN_EveryDayModelHelp startSetCalendar];
        //删除之前填充的初始化的model，方便增加新的日程
        [SN_USER.showCalendarArray removeLastObject];
        [SN_USER updateToDB];
         [tableView reloadData];
        }];
    rowAction.backgroundColor = SNCOLORBLACK;
    return @[rowAction];
}
//适配ios11，取消cell可以直接左滑到最左边删除的效果
- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos){
    // delete action
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:HHH_Text(@"删除") handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView,
        void (^ _Nonnull completionHandler)(BOOL)){
            [tableView setEditing:NO animated:YES];  // 这句很重要，退出编辑模式，隐藏左滑菜单
        //删除当前的model
        if(IOS10_OR_LATER){
            [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
        }else{
            [[UIApplication sharedApplication] cancelAllLocalNotifications];
        }
        [SN_USER.showCalendarArray removeObjectAtIndex:indexPath.row];
        
        //将数组中剩余model的orderIndex重置
        for (int i=0; i<SN_USER.showCalendarArray.count; i++) {
            SNcalendarModel *showModel =SN_USER.showCalendarArray[i];
            showModel.orderIndex=i;
            [SN_USER.showCalendarArray replaceObjectAtIndex:i withObject:showModel];
        }
        //往数组中添加初始化的model 便于覆盖calendarArray中的model
        SNcalendarModel *model = [[SNcalendarModel alloc]init];
        model.orderIndex =SN_USER.showCalendarArray.count;
        [SN_USER.showCalendarArray addObject:model];
        //覆盖
        for (int i=0; i<SN_USER.showCalendarArray.count; i++) {
            [SN_USER.calendarArray replaceObjectAtIndex:i withObject:SN_USER.showCalendarArray[i]];
        }
        [self resetNotificationWithArr:SN_USER.showCalendarArray];
        [SN_EveryDayModelHelp startSetCalendar];
        //删除之前填充的初始化的model，方便增加新的日程
        [SN_USER.showCalendarArray removeLastObject];
        [SN_USER updateToDB];
        [tableView reloadData];
        completionHandler(true);
    }];
    deleteAction.backgroundColor = SNCOLORBLACK;
    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    actions.performsFirstActionWithFullSwipe = NO;
    
    return actions;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//在日程到点并且被查看后或者日程被删除时，根据日程在数组中的顺序重新发送通知以显示正确的右上角角标数字，在此操作之前已经先删除之前发送的通知
-(void)resetNotificationWithArr:(NSMutableArray *)arr{
    for (int i=0; i<arr.count; i++) {
        SNcalendarModel *model = arr[i];
        if (IOS10_OR_LATER) {//ios 10
            if (model.open) {
                UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
                
                UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
                
                content.title = [NSString localizedUserNotificationStringForKey:SN_Text(@"日程") arguments:nil];
                
                content.body = [NSString localizedUserNotificationStringForKey:model.info arguments:nil];
                
                content.sound = [UNNotificationSound defaultSound];
                
                content.badge = [NSNumber numberWithInteger:model.orderIndex+1];
                
                NSCalendar *gregorian = [NSCalendar currentCalendar];
                
                NSDate* dt = model.date;
                unsigned unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth|
                NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
                
                NSDateComponents *components = [gregorian components:unitFlags fromDate:dt];
                
                UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
                NSString *identifier = [NSString stringWithFormat:@"Schedule%ld",model.orderIndex];
                UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
                
                [center addNotificationRequest:request withCompletionHandler:nil];
            }
        }else{
            if (model.open) {
                UILocalNotification *notification = [[UILocalNotification alloc] init];
                notification.timeZone = [NSTimeZone localTimeZone];
                notification.fireDate = model.date;
                notification.repeatCalendar=[NSCalendar currentCalendar];
                notification.alertBody = model.info;
                notification.alertAction = @"打开应用";
                notification.soundName = UILocalNotificationDefaultSoundName;
                notification.applicationIconBadgeNumber = model.orderIndex+1;
                [[UIApplication sharedApplication] scheduleLocalNotification:notification];
            }
        }
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
